// src/components/ImageViewer.tsx
import React, { useState, useEffect, useRef } from 'react';
import { View, Image, Swiper, SwiperItem, Text } from '@tarojs/components';
import './index.less';
import store from '@/src/store';
import Taro from '@tarojs/taro';

export interface ImageViewerProps {
  images: string[]; // 图片 URL 列表
  initialIndex?: number; // 初始展示的图片下标
  visible: boolean; // 是否可见
  onClose: () => void; // 关闭回调
}

const ImageViewer: React.FC<ImageViewerProps> = ({
  images,
  initialIndex = 0,
  visible,
  onClose,
}) => {
  const [current, setCurrent] = useState(initialIndex);
  const [duration, setDuration] = useState(300); // Swiper 动画时长（ms）
  const isVisibleRef = useRef(visible);

  // 设置导航栏颜色的安全方法
  const setNavBarColor = (isDark: boolean) => {
    try {
      Taro.setNavigationBarColor({
        frontColor: isDark ? '#ffffff' : '#000000',
        backgroundColor: isDark ? '#000000' : '#ffffff',
        animation: {
          duration: 300,
          timingFunc: 'easeInOut',
        },
      }).catch((err) => {
        console.warn('设置导航栏颜色失败:', err);
      });
    } catch (error) {
      console.warn('设置导航栏颜色异常:', error);
    }
  };

  // 监听小程序显示事件（从后台恢复）
  useEffect(() => {
    const handleShow = () => {
      // 如果当前组件是可见状态，重新设置导航栏
      if (isVisibleRef.current) {
        setNavBarColor(true);
      }
    };

    Taro.onAppShow(handleShow);

    return () => {
      Taro.offAppShow(handleShow);
    };
  }, []);

  // 更新 ref
  useEffect(() => {
    isVisibleRef.current = visible;
  }, [visible]);

  // 仅负责切换导航栏配色
  useEffect(() => {
    if (visible) {
      setNavBarColor(true);
    } else {
      setNavBarColor(false);
    }
  }, [visible]);

  // 当可见或外部 initialIndex 变化时：无动画直达目标下标
  useEffect(() => {
    if (!visible) return;
    // 先关动画，再设置 current，下一帧恢复动画
    setDuration(0);
    setCurrent(initialIndex);
    const t = setTimeout(() => setDuration(300), 50);
    return () => clearTimeout(t);
  }, [visible, initialIndex]);

  // 组件卸载时恢复导航栏
  useEffect(() => {
    return () => {
      if (isVisibleRef.current) {
        setNavBarColor(false);
      }
    };
  }, []);

  if (!visible) return null;

  const handleBackgroundClick = () => {
    onClose();
  };

  const handleSwiperClick = (e: any) => {
    e.stopPropagation();
  };

  const onChange = (e: any) => {
    setCurrent(e.detail.current);
  };

  return (
    <View
      className="image-viewer"
      style={{ paddingTop: `${store.commonStore.safeAreaTop}rpx` }}
      onClick={handleBackgroundClick}
    >
      {/* 图片左右滑动区 */}
      <View onClick={(e) => e.stopPropagation()} style={{ flex: 1 }}>
        <Swiper
          className="swiper"
          current={current}
          duration={duration}
          onChange={onChange}
          onClick={handleSwiperClick}
          indicatorDots={false}
          circular
          autoplay={false}
        >
          {images.map((url, idx) => (
            <SwiperItem key={idx}>
              <View className="slide-container">
                <Image src={url} className="slide-image" mode="widthFix" />
              </View>
            </SwiperItem>
          ))}
        </Swiper>
      </View>
      {/* 顶部页码 */}
      <Text
        className="counter"
        style={{ top: `${store.commonStore.pageAreaTop}rpx` }}
      >
        {current + 1}/{images.length}
      </Text>
    </View>
  );
};

export default ImageViewer;
